package ct.zxd.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ct.zxd.bean.Love;
import ct.zxd.db.TLoveDao;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class HandleLove
 */
public class HandleLove extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8;");
		TLoveDao tl = new TLoveDao();
		PrintWriter pw = response.getWriter();
		
		List<Love> loveList = new ArrayList<Love>() ;
		
		
		String flag = request.getParameter("flag") ;
		
		Integer dishId = (request.getParameter("dishId") == null ? 0 : Integer.parseInt(request.getParameter("dishId"))) ; //���ݿ���int
		String userId = request.getParameter("userId") ;
		
		if("add".equals(flag)) {
			pw.print(tl.insertLove(userId, dishId) > 0 ? "ok" : "no");
		}else if("del".equals(flag)) {
			pw.print(tl.deleteLoveByUserIdAndDishId(userId, dishId) > 0 ? "ok" : "no");
		}else if("findAll".equals(flag)) {
			loveList = tl.selectLoveByUserId(userId);
			JSONArray array = JSONArray.fromObject(loveList);
			pw.print(array);
		}else if("exist".equals(flag)){	
			pw.print(tl.isLoveByDishIdAndUserId(userId,dishId) == true ? "1" : "0");
		}else {
			pw.print("error");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
